package com.gitee.wsl.logger.format

import com.gitee.wsl.logger.LogPrinter
import com.gitee.wsl.logger.format


class JvmLogTxtPrettyFormat: LogTxtPrettyFormat() {
    override fun getStackTraceStringWithPrefix(thr: Throwable, s: String): Any {
        return stackTraceToStringBriefly(thr.stackTrace)
    }

    companion object{
        val instance = JvmLogTxtPrettyFormat()
    }

}


fun LogPrinter.useJvmLogTxtPrettyFormat() = format(JvmLogTxtPrettyFormat.instance)


/**
 * 获取以指定包名为前缀的最后n行简略栈追踪（方法名+包名）
 *
 * @param stackTraceElements 栈追踪元素
 * @param packagePrefix      包前缀
 * @param lineCount          行数
 * @return 栈追踪
 */
internal fun stackTraceToStringBriefly(
    stackTraceElements: Array<StackTraceElement>,
    packagePrefix: String? = "",
    lineCount: Int? = null,
    prefix:String? = null
): String {
    val s = StringBuilder()
    for (i in stackTraceElements.indices) {
        val stackTraceElement = stackTraceElements[i]

        // 如果是指定的包，则收集。（未指定也收集）
        if (packagePrefix.isNullOrEmpty() || stackTraceElement.className.startsWith(packagePrefix)
        ) {
            val info = stackTraceElement.methodName + ":" + stackTraceElement.lineNumber
            s.append(prefix).append(info)
        }

        // 如果指定了行数，则收集满了就退出。（不指定则全部收集）
        if (lineCount != null && i >= lineCount) {
            break
        }
    }
    return s.toString()
}